// components/scan-code/scan-code.js
import scanner from '../../utils/scanner';

Component({
  properties: {
    scanning: {
      type: Boolean,
      value: false
    }
  },

  data: {
    camera: false,
    error: ''
  },

  methods: {
    // 开始扫码
    startScan() {
      this.setData({ 
        camera: true,
        error: ''
      });
      this.triggerEvent('scanningChange', { scanning: true });
    },

    // 停止扫码
    stopScan() {
      this.setData({ camera: false });
      this.triggerEvent('scanningChange', { scanning: false });
    },

    // 扫码成功
    async onScanSuccess(e) {
      try {
        const scanResult = e.detail.result;
        
        // 解析扫码结果
        const sceneData = await scanner.parseCode(scanResult);
        
        // 更新扫码状态
        await scanner.updateScanStatus(sceneData.sceneId, 'SCANNED');
        
        // 触发扫码成功事件
        this.triggerEvent('scanSuccess', {
          sceneId: sceneData.sceneId,
          appId: sceneData.appId
        });
        
        // 关闭相机
        this.stopScan();
      } catch (error) {
        this.setData({ 
          error: error.message,
          camera: false
        });
        this.triggerEvent('scanError', { error: error.message });
      }
    },

    // 扫码错误
    onScanError(e) {
      this.setData({ 
        error: '扫码失败，请重试',
        camera: false
      });
      this.triggerEvent('scanError', { error: '扫码失败，请重试' });
    }
  }
});
